Repository navigation
Feat: Introduce LRU cache. - #138
Conversation
Codecov Report❌ Patch coverage is
Additional details and impacted files@@ Coverage Diff @@
## main #138 +/- ##
==========================================
- Coverage 88.55% 88.52% -0.03%
==========================================
Files 94 95 +1
Lines 4883 4985 +102
==========================================
+ Hits 4324 4413 +89
- Misses 369 378 +9
- Partials 190 194 +4
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
There was a problem hiding this comment.
1 issue found across 5 files
Prompt for AI agents (unresolved issues)
Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.
<file name="cache/lru.go">
<violation number="1" location="cache/lru.go:156">
P2: Overwriting an existing key invokes `OnEvict(EvictCapacity)` even though the entry was not evicted for capacity. `Put` calls `l.store.Remove(key)` for a present key before re-adding, which runs the hashicorp eviction callback with no reason stored, so the callback reports `EvictCapacity`; the same happens for `Delete` and `Purge`. `EvictionReason` is documented as describing why an item was removed (capacity vs TTL), but replacements and explicit deletes are labeled as capacity evictions. Any caller using `OnEvict` to free external resources only on genuine capacity eviction (or to distinguish reasons) will act incorrectly for every overwrite.</violation>
</file>
Tip: instead of fixing issues one by one fix them all with cubic
Re-trigger cubic
| } | ||
|
|
||
| // Put adds a value to the cache with the specified key and expiration time. | ||
| func (l *LRUStore[K, V]) Put(key K, value V, cacheDuration time.Duration) { |
There was a problem hiding this comment.
P2: Overwriting an existing key invokes OnEvict(EvictCapacity) even though the entry was not evicted for capacity. Put calls l.store.Remove(key) for a present key before re-adding, which runs the hashicorp eviction callback with no reason stored, so the callback reports EvictCapacity; the same happens for Delete and Purge. EvictionReason is documented as describing why an item was removed (capacity vs TTL), but replacements and explicit deletes are labeled as capacity evictions. Any caller using OnEvict to free external resources only on genuine capacity eviction (or to distinguish reasons) will act incorrectly for every overwrite.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At cache/lru.go, line 156:
<comment>Overwriting an existing key invokes `OnEvict(EvictCapacity)` even though the entry was not evicted for capacity. `Put` calls `l.store.Remove(key)` for a present key before re-adding, which runs the hashicorp eviction callback with no reason stored, so the callback reports `EvictCapacity`; the same happens for `Delete` and `Purge`. `EvictionReason` is documented as describing why an item was removed (capacity vs TTL), but replacements and explicit deletes are labeled as capacity evictions. Any caller using `OnEvict` to free external resources only on genuine capacity eviction (or to distinguish reasons) will act incorrectly for every overwrite.</comment>
<file context>
@@ -0,0 +1,201 @@
+}
+
+// Put adds a value to the cache with the specified key and expiration time.
+func (l *LRUStore[K, V]) Put(key K, value V, cacheDuration time.Duration) {
+ l.mu.Lock()
+ defer l.mu.Unlock()
</file context>
There was a problem hiding this comment.
Introduced delete, replace and purge evictionReasons.
roguepikachu
left a comment
There was a problem hiding this comment.
Took a pass on this. The overall shape looks right to me, hashicorp lru plus SizeOf and generics is what I was hoping for. A few things I think we should fix before helm starts depending on it, left them inline.
|
|
||
| if opts.SizeOf == nil { | ||
| opts.SizeOf = func(_ K, _ V) int64 { return 0 } | ||
| } |
There was a problem hiding this comment.
If MaxBytes is set and SizeOf is nil we silently count everything as 0, so the byte cap does nothing. I'd rather return an error here. SizeOf should be required when MaxBytes > 0.
There was a problem hiding this comment.
This looks good now. Constructor errors when MaxBytes is set and SizeOf is missing.
| val, ok := l.store.Peek(key) | ||
| if ok && val != nil && val.IsExpired() { | ||
| l.evictionReason.Store(key, EvictTTL) | ||
| l.store.Remove(key) |
There was a problem hiding this comment.
I think this has the same race we fixed on the TTL store. If a Put replaces this key between Peek and Remove, we delete the new value. Can we hold the lock across the expire check and remove, or only remove if the peeked entry is still the current one?
There was a problem hiding this comment.
Here it would be better to use the lock since for checking the previous value, we would again have to Peek and compare it with the previous Peek value.
There was a problem hiding this comment.
This is addressed. Sweep now holds the lock across the expire check and remove, so a concurrent Put cannot get wiped.
|
|
||
| if lc.IsExpired() { | ||
| l.evictionReason.Store(key, EvictTTL) | ||
| l.store.Remove(key) |
There was a problem hiding this comment.
Same concern here. Get then Remove is not atomic with Put, so a refresh can get wiped.
There was a problem hiding this comment.
This is addressed. Get now holds the lock for the expire check and remove.
| } | ||
|
|
||
| if prevValue, ok := l.store.Peek(key); ok && prevValue != nil { | ||
| l.store.Remove(key) |
There was a problem hiding this comment.
When we Remove before re-adding, OnEvict fires as capacity even though this is just an overwrite. Delete and Purge will look like capacity evictions too, and that will mess up helm metrics. Maybe skip OnEvict for explicit replace/delete, or add a distinct reason.
There was a problem hiding this comment.
The hashicorp-lru always fires the onEvict callback when we are using the Remove function. So instead of skipping the callback, adding a new reason EvictReplace would be a better options.
There was a problem hiding this comment.
Added the replace evictionReason.
| for atomic.LoadInt64(&l.currentMemory)+lc.memorySize > l.maximumMemory { | ||
| if oldestKey, _, ok := l.store.GetOldest(); ok { | ||
| l.evictionReason.Store(oldestKey, EvictCapacity) | ||
| } |
There was a problem hiding this comment.
Storing the reason by key in a side map feels racy to me. GetOldest then RemoveOldest can race with sweep, and a later Put of the same key can pick up the wrong reason. Could we keep the reason on the entry itself?
There was a problem hiding this comment.
Introduced a new reason and moved this reason to the lruCache struct so that now the reason is attached to the value being stored instead of the cache key.
There was a problem hiding this comment.
This is addressed. Reason lives on the entry now, so we are not racing on a side map keyed by K.
|
|
||
| // Put adds a value to the cache with the specified key and expiration time. | ||
| func (l *LRUStore[K, V]) Put(key K, value V, cacheDuration time.Duration) { | ||
| l.mu.Lock() |
There was a problem hiding this comment.
Put holds mu while OnEvict runs, but Get, Delete, and sweep don't take mu at all. If OnEvict calls Put we can deadlock on this path, and byte accounting can still race on the others. Can we lock all mutating paths the same way and fire OnEvict after unlocking?
There was a problem hiding this comment.
This is addressed in f200364. All mutating paths take the lock, and OnEvict runs after unlock via executeEviction.
There was a problem hiding this comment.
All reported issues were addressed across 2 files (changes from recent commits).
Reply with feedback, questions, or to request a fix.
Fix all with cubic | Re-trigger cubic
|
I re-ran this on the new head (f8b9bed). The race hardening is moving the right way, and SizeOf validation is a good fix. I still see one blocker and one follow-up concern, left inline. |
| atomic.AddInt64(&lc.currentMemory, -value.memorySize) | ||
| } | ||
| if lc.OnEvict != nil && value != nil { | ||
| lc.OnEvict(key, value.data, value.evictionReason) |
There was a problem hiding this comment.
Blocking: OnEvict is still called while l.mu is held by Put/Get/Delete/Purge/sweep paths that trigger store.Remove/RemoveOldest/Purge. If callback code re-enters the same store (for example Put on eviction), this deadlocks because sync.Mutex is not re-entrant. I would buffer evicted items while locked and invoke OnEvict after unlocking.
There was a problem hiding this comment.
Introduced a new field for the LRUStore and a new function which first does the unlocking and then goes on to execute the onEvict callback.
There was a problem hiding this comment.
This is addressed. Buffering pendingEvicts and firing OnEvict after unlock is what I wanted here.
| } | ||
|
|
||
| lru, err := hashicorp.NewWithEvict(opts.MaxSize, func(key K, value *lruCache[V]) { | ||
| if value != nil && opts.MaxBytes != 0 { |
There was a problem hiding this comment.
Follow-up: CurrentBytes accounting still only updates when MaxBytes != 0. With unlimited MaxBytes plus SizeOf configured, CurrentBytes remains 0, which breaks observability callers that want usage without enforcing a hard cap.
There was a problem hiding this comment.
Have removed the additional condition of opts.MaxBytes
There was a problem hiding this comment.
Still pending on b539a09.
Put only sets memorySize and updates currentMemory when maximumMemory != 0, so with MaxBytes: 0 and a SizeOf configured, CurrentBytes() stays 0.
Please track whenever SizeOf is set, and only use MaxBytes for the eviction budget.
There was a problem hiding this comment.
Add the memory of the value to the currentMemory for updation when sizeOf is set. Added a separate conditoin for memory addition when sizeOf is present even if the maximumMemory is 0.
|
@kash2104, could you resolve all comments that are addressed and also take a look at the cubic comments? Happy to re-review it once these are done. Thanks! |
|
Hey @roguepikachu , have addressed the bot comments and review suggestions. |
Signed-off-by: kash2104 <kparikh1104@gmail.com>
Signed-off-by: kash2104 <kparikh1104@gmail.com>
Signed-off-by: kash2104 <kparikh1104@gmail.com>
Add eviction reason for delete and purge. Signed-off-by: kash2104 <kparikh1104@gmail.com>
|
Hey @kash2104 #138 (comment), this still remains unaddressed please have a look. |
…s set. Signed-off-by: kash2104 <kparikh1104@gmail.com>
|
Hey @roguepikachu , updated the |
roguepikachu
left a comment
There was a problem hiding this comment.
Nits on unused defaults + comment cleanup (non-blocking polish before merge):
- Drop or actually use
DefaultLRUCacheMemory/DefaultLRUCacheSize - Fix/tighten a few comments (
NewLRUCache,IsExpired, narrating Put comment, and the test placeholder)
No unused imports spotted in cache/; the dead surface is those unused consts.
There was a problem hiding this comment.
@kash2104 Nits on unused defaults + comment cleanup (non-blocking polish before merge):
- Drop or actually use
DefaultLRUCacheMemory/DefaultLRUCacheSize - Fix/tighten a few comments (
NewLRUCache,IsExpired, narrating Put comment, and the test placeholder)
No unused imports spotted in cache/; the dead surface is those unused consts.
| DefaultLRUCacheMemory = 1024 * 1024 * 256 // 256MB | ||
| // DefaultLRUCacheSize for LRUCacheMemoryStore | ||
| DefaultLRUCacheSize = 1000 | ||
| ) |
There was a problem hiding this comment.
Nit: DefaultLRUCacheMemory / DefaultLRUCacheSize are unused (nothing in this repo or the consumer PRs references them; kubevela hardcodes 256 << 20 instead).
Please either drop them, or wire them as the real defaults in NewLRUStore / the Helm provider so they are not dead API surface.
There was a problem hiding this comment.
Currently would be dropping these since in the follow-up, we are introducing cli flag for setting these fields and fallback to default in the kubevela repo would be a better option instead of using the constants from pkg repo
| } | ||
|
|
||
| // NewLRUCache new lru cache instance | ||
| func NewLRUCache[V any](data V, cacheDuration time.Duration) *lruCache[V] { |
There was a problem hiding this comment.
Nit (comment cleanup): please use a normal Go doc, e.g.
// NewLRUCache creates an LRU cache entry with the given value and TTL.| } | ||
|
|
||
| // isExpired whether the cache data expires | ||
| func (l *lruCache[V]) IsExpired() bool { |
There was a problem hiding this comment.
Nit (comment cleanup): godoc name does not match the method. Please use:
// IsExpired reports whether the cache entry's TTL has elapsed.| } | ||
|
|
||
| // Update the current memory usage after adding the new item to the cache if sizeOf is provided | ||
| if l.sizeOf != nil { |
There was a problem hiding this comment.
Nit (comment cleanup): this comment only restates the next few lines. Prefer deleting it, or keep a short why note if needed (e.g. that we track bytes whenever sizeOf is set, even when MaxBytes == 0).
| store.Put("b", "world", 0) | ||
| store.Purge() | ||
| // placeholder-noop-keep-context | ||
|
|
There was a problem hiding this comment.
Nit: please delete // placeholder-noop-keep-context. Looks like a leftover placeholder and does not help the test.
Signed-off-by: kash2104 <kparikh1104@gmail.com>
Signed-off-by: kash2104 <kparikh1104@gmail.com>
|
Thank you for your contribution @kash2104 ! |
This PR introduces an LRU cache backed by hashicorp/golang-lru.
Along with the cache implementation, it provides configurable cache options that allow the LRU cache to support byte-based memory accounting in addition to the standard entry-count limit.
The cache provides the following operations:
These operations have been implemented to account for the configured byte limit and maintain the current memory usage of the cache accordingly.
The cache also supports configurable cache expiration and periodic sweeping of expired entries.
Summary by cubic
Introduces a generic, thread-safe LRU cache with per-item TTL, byte budgets, and post-unlock eviction callbacks for predictable, race-free in-memory caching. No existing code paths change.
LRUStore[K,V]with Get/Put/Delete, plus Purge and CurrentBytes; Put accepts per-item TTL.LRUCache,Options, andEvictionReasonincache/cache.go; addsgithub.com/hashicorp/golang-lru/v2.Written for commit 4bdf3b1. Summary will update on new commits.